package org.geektimes.projects.user.web.listener;

import org.geektimes.projects.user.sql.DataSourceDBConnectionManager;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
//配置 web.xml文件中的 web-app 标签下，metadata-complete = false 就会去扫描这些3.0以后支持的注解
//@WebListener
public class DBConnectionInitializerListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("==>>DBConnectionInitializerListener#contextInitialized");
        final ServletContext servletContext = sce.getServletContext();
        String databaseURL = "jdbc:derby:/db/user-platform;create=true";
        try {
            //Connection connection = DriverManager.getConnection(databaseURL);
            //DBConnectionManager dbConnectionManager = DBConnectionManager.getInstance();
            //dbConnectionManager.setConnection(connection);
            //servletContext.setAttribute("dbConnectionManager",dbConnectionManager);

            // Obtain our environment naming context
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");

            // Look up our data source
            DataSource ds = (DataSource)envCtx.lookup("jdbc/UserPlatformDB");

            DataSourceDBConnectionManager dataSourceDBConnectionManager = DataSourceDBConnectionManager.getInstance();
            dataSourceDBConnectionManager.setDataSource(ds);

            // Allocate and use a connection from the pool
            //Connection conn = ds.getConnection();
            //... use this connection to access the database ...
            //conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("==>>DBConnectionInitializerListener#contextDestroyed");

    }
}
